
package com.seekting.study;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * 集合并交减
 */
public class ListOprations {

    public static void main(String[] args) {

        List<Integer> server = new ArrayList<Integer>();
        server.add(1);
        server.add(2);
        server.add(3);
        List<Integer> local = new ArrayList<Integer>();
        local.add(0);
        local.add(2);
        local.add(3);
        local.add(4);

        List<Integer> intersect = intersect(server, local);
        print("intersect", intersect);
        List<Integer> union = union(server, local);
        print("union", union);
        List<Integer> diff = diff(server, local);
        print("diff", diff);
        List<Integer> diff1 = diff(local, server);
        print("diff1", diff1);
    }

    /**
     * 交集
     * 
     * @param ls
     * @param ls2
     * @return
     */
    public static List<Integer> intersect(List<Integer> ls, List<Integer> ls2) {
        List<Integer> result = new ArrayList<Integer>(Arrays.asList(new Integer[ls.size()]));
        Collections.copy(result, ls);
        result.retainAll(ls2);
        return result;

    }

    /**
     * 并集
     * 
     * @param ls
     * @param ls2
     * @return
     */
    public static List<Integer> union(List<Integer> ls, List<Integer> ls2) {
        List<Integer> result = new ArrayList<Integer>(Arrays.asList(new Integer[ls.size()]));
        Collections.copy(result, ls);
        // result.containsAll(ls2);
        for (int i = 0; i < ls2.size(); i++) {
            if (!result.contains(ls2.get(i))) {
                result.add(ls2.get(i));
            }
        }
        // result.addAll(ls2);
        return result;

    }

    /**
     * 并集
     * 
     * @param ls
     * @param ls2
     * @return
     */
    public static List<Integer> diff(List<Integer> ls, List<Integer> ls2) {
        List<Integer> result = new ArrayList<Integer>(Arrays.asList(new Integer[ls.size()]));
        Collections.copy(result, ls);
        result.removeAll(ls2);
        return result;

    }

    public static void print(String tag, List<Integer> ls) {
        System.out.print(tag + ":");
        for (int i = 0; i < ls.size(); i++) {
            System.out.print(ls.get(i));
        }
        System.out.println();
    }
}
